package com.SmartTest7_17;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.os.Environment;
import android.util.Base64;

public class EncodeUtilPlugin extends CordovaPlugin {
	
	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) 
			throws JSONException {
		if (action.equals("encodeAudio")){
			try {
				String responseText = encodeAudio(args.getString(0));
				callbackContext.success(responseText);
			} catch (JSONException e1){
				callbackContext.error("Failed to parse parameters");
			} catch(IOException e2) {
				callbackContext.error("IOExceptioin");
			}
			return true;
		} else if(action.equals("decodeAudio")) {
			try {
				String responseText = decodeAudio(args.getString(0));
				callbackContext.success(responseText);
			} catch (JSONException e1){
				callbackContext.error("Failed to parse parameters");
			} catch (IOException e2) {
				callbackContext.error("IOExceptioin");
			}
			return true;
		}
		return false;
	}
	
	public static String encodeAudio(String filePath) throws IOException {
		String recordPath = Environment.getExternalStorageDirectory() + "/" + filePath;
		File file = new File(recordPath);
		if(!file.exists()) {
			return "file not exist:";
		}
		byte[] bytes = null;
		try {
			bytes = getByte(file);
		} catch (Exception e1) {
			return "get byte fail";
		}
		String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);                     
		file.delete();
		return encodedString;
	}
	
	public static String decodeAudio(String encodedContent) throws IOException{
		byte[] decoded = Base64.decode(encodedContent, Base64.DEFAULT);
		String dirPath = Environment.getExternalStorageDirectory() + "/";
//		File dir = new File(dirPath);
//		if(!dir.exists())
//			dir.mkdir();
		
		String recordPath = dirPath + "play.ogg";
		File file = new File(recordPath);
		file.delete();
	    if(!file.exists())
	    	file.createNewFile();
	    
	    FileOutputStream os = new FileOutputStream(file, true);
	    os.write(decoded);
	    os.close();
		return Arrays.toString(decoded);
	}
	
	public static byte[] getByte(File file) throws Exception {  
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));        
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);        
        byte[] temp = new byte[1024];        
        int size = 0;        
        while ((size = in.read(temp)) != -1) {        
            out.write(temp, 0, size);        
        }        
        in.close();        
        byte[] content = out.toByteArray(); 
        return content;  
    }  
}
